package com.atguigu.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.exception.ziDyException;
import com.atguigu.yygh.enums.PaymentTypeEnum;
import com.atguigu.yygh.enums.RefundStatusEnum;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.model.order.RefundInfo;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.order.service.PaymentInfoService;
import com.atguigu.yygh.order.service.RefundInfoService;
import com.atguigu.yygh.order.service.WeixinService;
import com.atguigu.yygh.order.utils.ConstantPropertiesUtils;
import com.atguigu.yygh.order.utils.HttpClient;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class WeixinServiceImpl implements WeixinService {

    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private PaymentInfoService paymentInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RefundInfoService refundInfoService;

    @Override
    public Map createNative(Long orderId) {

        //1. 根据orderid去查询订单信息
        OrderInfo byIdOrder = orderInfoService.findByIdOrder(orderId);
        if (byIdOrder == null){
            throw new ziDyException(20001,"没有此订单");
        }
        //将订单信息存到交易记录表中、
        paymentInfoService.savePaymentInfo(byIdOrder, PaymentTypeEnum.WEIXIN.getStatus());


        try {
            //生成支付的二维码，封装数据，调用微信的服务接口
            //1、设置参数，这些参数都是固定的
            Map paramMap = new HashMap();
            //自己的appid
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            //商户号
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            //设置要返回的数据，这个是在支付者的手机上显示的内容
            Date reserveDate = byIdOrder.getReserveDate();
            String reserveDateString = new DateTime(reserveDate).toString("yyyy/MM/dd");
            String body = reserveDateString + "就诊"+ byIdOrder.getDepname();
            paramMap.put("body", body);

            paramMap.put("out_trade_no", byIdOrder.getOutTradeNo());
            //paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
            paramMap.put("total_fee", "1");//为了测试
            paramMap.put("spbill_create_ip", "127.0.0.1");
            //回调地址
            paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
            //支付方式类型
            paramMap.put("trade_type", "NATIVE");

            //设置使用httpclient调用对象
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();

            //获取微信给我们返回的数据
            String content = client.getContent();//返回的这个默认是xml文件格式的
            //将xml文件转换成map格式，可以是用微信给我们提供的工具类
            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);


            //封装map返回数据
            Map map = new HashMap();
            map.put("orderId", orderId);
            map.put("totalFee", byIdOrder.getAmount());
            map.put("resultCode", resultMap.get("result_code"));
            map.put("codeUrl", resultMap.get("code_url"));

            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    //调用第三方接口，查询订单的支付状态，是否支付成功
    @Override
    public Map<String, String> queryPayStatus(Long orderId, String paymentType) {

        //首先先查询订单信息
        OrderInfo orderInfo = orderInfoService.getById(orderId);
        if (orderInfo == null){
            throw new ziDyException(20001,"数据错误");
        }
        //1、封装参数
        Map paramMap = new HashMap<>();
        paramMap.put("appid", ConstantPropertiesUtils.APPID);
        paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
        //订单的交易号
        paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
        //必须传递的一个随机字符串，微信官方要求
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());


        try {
            //创建连接,这个是微信官网的回调接口
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            //设置参数
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();

            //返回回调回来的数据
            String content = client.getContent();
            //将数据转换成map
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            System.out.println("map = " + map.toString());
            //返回数据
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
    //微信退款方法
    @Override
    public Boolean refund(Long orderId) {

        //使用orderid查询出交易记录
        PaymentInfo paymentInfo = paymentInfoService.getPaymentInfo(orderId, PaymentTypeEnum.WEIXIN.getStatus());

        //将交易记录添加到退款记录中
        RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
        //这里判断是否已经退款了，防止重复操作
        if (refundInfo.getRefundStatus().intValue() == RefundStatusEnum.REFUND.getStatus().intValue()){
            return true;
        }

        //封装退款传递的参数
        Map<String,String> paramMap = new HashMap<>(8);
        paramMap.put("appid",ConstantPropertiesUtils.APPID);       //公众账号ID
        paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);   //商户编号
        paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
        paramMap.put("transaction_id",paymentInfo.getTradeNo()); //微信订单号
        paramMap.put("out_trade_no",paymentInfo.getOutTradeNo()); //商户订单编号
        paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo()); //商户退款单号
        //       paramMap.put("total_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
        //       paramMap.put("refund_fee",paymentInfoQuery.getTotalAmount().multiply(new BigDecimal("100")).longValue()+"");
        paramMap.put("total_fee","1");
        paramMap.put("refund_fee","1");

        try {
            //创建连接，调用微信的退款接口
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            //将传递的参数转换为xml格式，第二个参数是商户号
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            //是否使用cert证书进行退款
            client.setCert(true);
            //证书密码，这里的密码默认就是商户id
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);
            client.post();

            //接收微信退款返回的参数
            String content = client.getContent();
            //将参数转换为map类型
            Map<String, String> map = WXPayUtil.xmlToMap(content);
            //判断是否退款成功
            if (null != map && WXPayConstants.SUCCESS.equalsIgnoreCase(map.get("result_code"))) {
                //退款成功以后修改退款表中的数据
                //回调时间
                refundInfo.setCallbackTime(new Date());
                //交易编号
                refundInfo.setTradeNo(map.get("refund_id"));
                //退款状态
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                //回调内容
                refundInfo.setCallbackContent(JSONObject.toJSONString(map));
                //进行修改
                refundInfoService.updateById(refundInfo);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
